package com.basic.datapersist;

import java.util.Date;
import java.util.HashMap;

import org.apache.log4j.Logger;
 
 
public abstract class BaseOneRow implements OneRowDataInit{
	private static Logger logger = Logger.getLogger ( BaseOneRow.class ) ;
	protected CatchOneRowData rowData = new CatchOneRowData();
	private DbConnectTool connect = null;
	private DbBasicService tmpService = null;
	private DbBasicService dbTransService = null;
 	 
	protected abstract MapTable getMapTable() ;
	
	@Override
	public void putData(HashMap<String, String> map){
		rowData.putData(map);
	}
	
	protected DbBasicService getDbService(){
		if(dbTransService != null){
			dbTransService.setMapTable(getMapTable());
			return dbTransService;
		}
		tmpService = DbFactory.instance(connect, DbBasicService.class);
		tmpService.setMapTable(getMapTable());
		return tmpService;
	}
	protected void freeDbService() throws Exception{
		if(tmpService != null){
			tmpService.commit();
			tmpService.freeResource();
			tmpService = null;
		}
	}
	public void useTransaction(DbBasicService dbService){
		this.dbTransService = dbService;
		this.dbTransService.setMapTable(getMapTable());
	}
	@Override
	public void initByKey(Object key) throws Exception {
		try {
			ConditionTool tool = new ConditionTool();
			tool.setCondition(getMapTable().getKeyColumns(), key.toString());
			
			DbBasicService dbservice = this.getDbService();
			dbservice.setConditionTool(tool);
			rowData.putData(dbservice.queryExec().get(0));
		}
		finally{
			freeDbService();
		}
	}
	@Override
	public void initConnect(DbConnectTool connect){
		this.connect = connect;
	}
	 
	public void insert() throws Exception {
		try {
			DbBasicService dbservice = this.getDbService();
			dbservice.setNewData(rowData.getNewData());
			dbservice.insertExec();
		} finally{
			freeDbService();
		}
	}
	
	public void update() throws Exception {
		try {
			ConditionTool tool = new ConditionTool();
			tool.setCondition(getMapTable().getKeyColumns(), rowData.getValue(getMapTable().getKeyColumns()));
			
			DbBasicService dbservice = this.getDbService();
			dbservice.setNewData(rowData.getNewData());
			dbservice.setConditionTool(tool);
			dbservice.updateExec();
		} finally{
			freeDbService();
		}
	}
	
	public void delete() throws Exception {
		try {
			ConditionTool tool = new ConditionTool();
			tool.setCondition(getMapTable().getKeyColumns(), rowData.getValue(getMapTable().getKeyColumns()));
			
			DbBasicService dbservice = this.getDbService();
			dbservice.setConditionTool(tool);
			dbservice.deleteExec();
		}
		finally{
			freeDbService();
		}
	}
	public void printData(){
		rowData.printNewData();
	}
}
